package com.zhike.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhike.constant.HbaseConstant;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.util.List;

/**
 * @Author: zhike
 * @CreateTime: 2024/1/29 11:22
 * @Description: 维度查询工具类
 */
public class DimUtils {
    public static JSONObject getDimInfo(Connection connection, String tableName, String key) throws Exception {
        //先查询redis
        Jedis jedis = JedisUtils.getJedis();
        String redisKey = "DIM:" + tableName + ":" + key;
        String dimJsonStr = jedis.get(redisKey);
        if (dimJsonStr != null) {
            //重置过期时间
            jedis.expire(redisKey, 24 * 60 * 60);
            //归还连接
            jedis.close();
            //返回维度数据
            return JSON.parseObject(dimJsonStr);
        }

        //拼接sql
        String querySql = "select * from " + HbaseConstant.HBASE_SCHEMA + "." + tableName + " where ID='" + key + "'";
        List<JSONObject> queryList = JdbcUtils.queryList(connection, querySql, JSONObject.class, false);

        //将从phonex中查到的数据写到redis
        JSONObject dimInfo = queryList.get(0);
        jedis.set(redisKey, dimInfo.toJSONString());
        //设置过期时间
        jedis.expire(redisKey, 24 * 60 * 60);
        //关闭连接
        jedis.close();
        return dimInfo;
    }

    public static void delDimInfo(String tableName, String key) {
        //获取连接
        Jedis jedis = JedisUtils.getJedis();
        //删除redis数据
        jedis.del("DIM:" + tableName + ":" + key);
        //关闭连接
        jedis.close();
    }

}
